package com.xywy.common.app;

import java.io.File;
import java.util.HashSet;
import java.util.Set;

import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.graphics.Bitmap;

import com.baidu.frontia.FrontiaApplication;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.xywy.common.FragmentMainActivity;
import com.xywy.common.util.MLog;
import com.xywy.common.util.ble.util.BLEBloodPresureProvider;
import com.xywy.common.util.ble.util.BLEWeightScaleProvider;
import com.xywy.me.bean.User;

/**
 * 名称: MainApplication 描述: Application 主类 最近修改时间:2014-04-24 9:10
 * 
 * @author xiaogd
 * @since 2014-04-24
 */
public class MainApplication extends FrontiaApplication {

	private static final String TAG = "MainApplication";
	private HttpClient httpClient;
	private static Set<Activity> activitys;
	private static Set<Activity> speciallActivitys; // 特殊的activity
	private static boolean isFirstOpenAPp = true; // 判断本应用是否第一次开启，控制第一次使用应用时，weight中威未连接的框
	private BLEWeightScaleProvider bleWeightScaleProvider;// 蓝牙适配器，寻找蓝牙等位置使用；
															// 体重秤
	private BLEBloodPresureProvider bleBloodPresureProvider;// 蓝牙适配器，寻找蓝牙等位置使用；
															// 血压计

	private static MainApplication app;

	public MainApplication() {
	}

	public static MainApplication getInstance() {
		return app;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		app = this;
		httpClient = this.createHttpClient();
		MLog.d(TAG, " MainApplication onCreate");
		// 配置ImageLoader框架
		setImageLoader();
		// 初始化高德定位
		setGaodeLocation();
		// 用于存储所有的activity信息
		activitys = new HashSet<Activity>();
		speciallActivitys = new HashSet<Activity>();
		// 初始化设备信息
		DeviceInfo.init(this);
		initBle();
//		 CrashHandler.getInstance().init(getApplicationContext()); 
	}

	/**
	 * 将体重蓝牙引用开启；
	 */
	private void initBle() {
		bleWeightScaleProvider = BLEWeightScaleProvider.getInstance();
		bleWeightScaleProvider.init(this);
		bleBloodPresureProvider = BLEBloodPresureProvider.getInstance();
		bleBloodPresureProvider.init(this);
	}

	/**
	 * 获取当前体重蓝牙的adapter
	 * 
	 * @return
	 */
	public BluetoothAdapter getWeightBleAdapter() {
		return bleWeightScaleProvider.getBLEAdatper();
	}

	/**
	 * 获取当前的体重秤蓝牙管理引用；
	 * 
	 * @return
	 */
	public BLEWeightScaleProvider getWeightBleProvider() {
		return bleWeightScaleProvider;
	}

	/**
	 * 获取当前血压计蓝牙管理引用；
	 * 
	 * @return
	 */
	public BLEBloodPresureProvider getBloodPBleProvider() {
		return bleBloodPresureProvider;
	}

	/**
	 * 对外提供 HttpClient 实例
	 */
	public HttpClient getHttpClient() {
		return httpClient;
	}

	/**
	 * 关闭连接管理器并释放资源
	 */
	private void shutdownHttpClient() {
		if (httpClient != null && httpClient.getConnectionManager() != null) {
			httpClient.getConnectionManager().shutdown();
		}
	}

	/**
	 * 重新获取httpClient
	 * 
	 * @return
	 */
	public boolean reStartClient() {
		if (null != httpClient) {
			httpClient = createHttpClient();
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 配置ImageLoader框架
	 */
	public void setImageLoader() {
		File cacheDir = StorageUtils.getCacheDirectory(getApplicationContext());
		// 可使用默认的配置, 如下:
		// ImageLoaderConfiguration
		// config=ImageLoaderConfiguration.createDefault(this);
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				this)
				// 内存缓存最大图片尺寸
				.memoryCacheExtraOptions(480, 400)
				// default = device screen dimensions
				// SD卡缓存最大图片尺寸
				.discCacheExtraOptions(480, 400, Bitmap.CompressFormat.JPEG,
						75, null)

				// 工作线程数量
				.threadPoolSize(3)
				.threadPriority(Thread.NORM_PRIORITY - 1)
				// default
				.tasksProcessingOrder(QueueProcessingType.FIFO)
				// default
				.denyCacheImageMultipleSizesInMemory()
				// default
				// LRU缓存大小
				.memoryCache(new LruMemoryCache(2 * 1024 * 1024))
				// 内存缓存大小
				.memoryCacheSize(2 * 1024 * 1024).memoryCacheSizePercentage(13)
				// SD卡缓存，The fastest cache, doesn't limit cache size
				.discCache(new UnlimitedDiscCache(cacheDir))
				// SD卡缓存大小
				.discCacheSize(50 * 1024 * 1024).discCacheFileCount(100)
				.discCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
				.imageDownloader(new BaseImageDownloader(this)) // default
				.defaultDisplayImageOptions(DisplayImageOptions.createSimple())// default
				.writeDebugLogs().build();

		ImageLoader.getInstance().init(config);
	}

	/**
	 * 初始化高德定位
	 */
	public void setGaodeLocation() {

	}

	/**
	 * 创建httpclient实例
	 * 
	 * @return
	 */
	private HttpClient createHttpClient() {
		HttpParams params = new BasicHttpParams();
		params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000);// 设置数据等待超时
		params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); // 设置连接超时
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
		HttpProtocolParams.setUseExpectContinue(params, true);
		SchemeRegistry schReg = new SchemeRegistry();
		schReg.register(new Scheme("http", PlainSocketFactory
				.getSocketFactory(), 80));
		// schReg.register(new
		// Scheme("https",SSLSocketFactory.getSocketFactory(), 443));
		ClientConnectionManager connMgr = new ThreadSafeClientConnManager(
				params, schReg);
		return new DefaultHttpClient(connMgr, params);
	}

	/**
	 * activity开启
	 * 
	 * @param activity
	 * @return
	 */
	public static boolean add(Activity activity) {

		boolean b = false;
		if (activity != null) {
			b = activitys.add(activity);
		}
		return b;
	}

	/**
	 * activity结束
	 * 
	 * @param activity
	 * @return
	 */
	public static boolean remove(Activity activity) {
		boolean b = false;
		if (null != activity) {
			Object obj = activitys.remove(activity);
			if (null == obj) {
				b = false;
			} else {
				MLog.i(TAG, "移除了" + activity.getClass().getSimpleName());
				b = true;
			}
		}
		System.gc();
		return b;
	}

	/**
	 * 退出
	 */
	public void exit() {
		// 清除所有activity
		for (Activity a : activitys) {
			if (null != a) {
				a.finish();
			}
		}
		// android.os.Process.killProcess(android.os.Process.myPid());
		// System.exit(0);
	}

	/**
	 * 添加特殊的activity
	 * 
	 * @param activity
	 */
	public static void addSpeciall(Activity activity) {
		if (activity != null) {
			speciallActivitys.add(activity);
		}
	}

	/**
	 * 移除上面特殊的activity
	 */
	public static void finishSpeciall() {
		for (Activity a : speciallActivitys) {
			if (null != a) {
				a.finish();
			}
		}
	}

	static FragmentMainActivity mActivity;

	public static void setMainActivity(FragmentMainActivity activity) {
		mActivity = activity;
	}

	public static FragmentMainActivity getMainActivity() {
		return mActivity;
	}

	public static boolean isFirstOpenAPp() {
		return isFirstOpenAPp;
	}

	public static void setFirstOpenAPp(boolean isFirstOpenAPp) {
		MainApplication.isFirstOpenAPp = isFirstOpenAPp;
	}

}
